package cn.sisyphe.framework.common.bootstrap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.lang.management.ManagementFactory;
import java.util.*;

/**
 * Created by heyong on 2017/10/11 9:39
 * Description:
 * @author heyong
 */
public class Bootstrap {

    private static final Logger logger = LoggerFactory.getLogger(Bootstrap.class);

    private static List<StartupListener> listenerList = null;

    public static void before(){
        ServiceLoader<StartupListener> loader = ServiceLoader.load(StartupListener.class);
        listenerList = new ArrayList<>();
        for (StartupListener listener : loader){
            listenerList.add(listener);
        }

        listenerList.sort(Comparator.comparing(StartupListener::getOrder));

        logger.info("*********************初始化StartupListener*************************");
        if (!listenerList.isEmpty()) {
            for (StartupListener listener : listenerList) {
                listener.init();
                logger.info("   {0} 初始化", listener.getClass().getName());
            }
        }

        logger.info("====================>准备加载Spring配置文件<====================");
    }

    public static void after(ApplicationContext context) {
        logger.info("====================>Spring配置文件加载完毕<====================");

        if (!listenerList.isEmpty()) {
            for (StartupListener listener : listenerList) {
                listener.complete(context);
                logger.info("   {0} 初始化成功。", listener.getClass().getName());
            }
        }

        logger.info("**********************************************************");

        System.out.println(new StringBuilder().append("\n***************************************").append('\n')
                .append("         ").append(ManagementFactory.getRuntimeMXBean().getName()).append('\n').append("         ")
                //.append(PropertyHolder.getProjectName()).append("模块启动成功！").append('\n')
                .append("***************************************"));
        logger.info("====================>系统正常启动<====================");

    }
}
